<template>
	<view>
		<form>
			<view class="cu-form-group">
				<view class="title">名称</view>
				<input v-model="form.name" placeholder="请输入商品名称" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">分类</view>
				<view v-if="checkedClassifyList.length" class="classify-list" @tap="showModal" data-target="ChooseModal">
					<view class="classify-item bg-green" v-for="(item, index) in checkedClassifyList" :key="index" :data-id="item._id" :data-index="index"  @click.stop="deleteClassify">
						<text>{{item.name}}</text>
						<uni-icons class="close-icon" type="clear"></uni-icons>
					</view>
				</view>
				<input v-else disabled placeholder="请选择商品分类" @tap="showModal" data-target="ChooseModal"></input>
			</view>
			
			<view class="cu-bar bg-white margin-top">
				<view class="action">
					轮播图
				</view>
				<view class="action">
					{{bannerImgList.length}}/4
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in bannerImgList" :key="index" @tap="viewImage" :data-url="item.tempFile">
					 <view class="shade" v-if="!item.complete"></view>
					 <image :src="item.tempFile" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="delImg" data-target="banner" :data-index="index" v-if="item.complete">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="chooseImage('banner')" v-if="bannerImgList.length<4">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="cu-bar bg-white">
				<view class="action">
					详情图
				</view>
				<view class="action">
					{{detailImgList.length}}/4
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in detailImgList" :key="index" @tap="viewImage" :data-url="item.tempFile">
					 <view class="shade" v-if="!item.complete"></view>
					 <image :src="item.tempFile" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="delImg" data-target="detail" :data-index="index" v-if="item.complete">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="chooseImage('detail')" v-if="detailImgList.length<4">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="sku-list">
				<view class="sku-title">
					<text>规格</text>
					<text class="text-green" @tap="showSkuModal" data-target="skuModal">添加规格</text>
				</view>
				<view class="sku-wrap">
					<view class="sku-item title">
						<text class="name">名称</text>
						<text class="price">原价</text>
						<text class="price">折扣价</text>
						<text class="count">库存</text>
						<text class="operation">操作</text>
					</view>
					<view class="sku-item" v-for="(item, index) in form.skuList" :key="index">
						<text class="name">{{item.name}}</text>
						<text class="price">{{item.originalPrice}}</text>
						<text class="price">{{item.discountPrice}}</text>
						<text class="count">{{item.repertory}}</text>
						<text class="operation">
							<text class="icon cuIcon-edit text-blue" @tap="showSkuModal" data-target="skuModal" :data-index="index"></text>
							<text class="icon cuIcon-delete text-red" @tap="deleteSku" :data-index="index"></text>
						</text>
					</view>
				</view>
			</view>
		</form>
		<view class="operation-btn-wrap">
			<button class="cu-btn round bg-green margin-tb-sm lg operation-btn" @tap.stop="submitForm">确 定</button>
			<button class="cu-btn round bg-white margin-tb-sm lg operation-btn" @tap="cancel">取 消</button>
		</view>
		<view class="cu-modal bottom-modal" :class="modalName=='skuModal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideModal">取消</view>
					<view class="action text-green" @tap="submitSkuForm">确定</view>
				</view>
				<view class="padding-xl">
					<view class="cu-form-group">
						<view class="title">名称</view>
						<input v-model="skuForm.name" placeholder="请输入商品名称" name="input"></input>
					</view>
					<view class="cu-form-group">
						<view class="title">原价</view>
						<input v-model="skuForm.originalPrice" placeholder="请输入原价" type="number"></input>
					</view>
					<view class="cu-form-group">
						<view class="title">折扣价</view>
						<input v-model="skuForm.discountPrice" placeholder="请输入折扣价" type="number"></input>
					</view>
					<view class="cu-form-group">
						<view class="title">库存</view>
						<input v-model="skuForm.repertory" placeholder="请输入库存" type="number"></input>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-modal bottom-modal" :class="modalName=='ChooseModal'?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideModal">取消</view>
					<view class="action text-green" @tap="editClassify()">确定</view>
				</view>
				<view class="grid col-3 padding-sm">
					<view v-for="(item,index) in classifyList" class="padding-xs" :key="index">
						<button class="cu-btn green lg block" :class="item.checked?'bg-green':'line-green'" @tap="chooseCheckbox"
						 :data-value="item._id"> {{item.name}}
						</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import goodsApi from '@/api/goods.js';
	import config from '@/config.js';
	import utils from '@/utils/util.js';
	import {isEmpty} from '@/utils/validate.js';
	export default {
		data() {
			return {
				goodsId: '',
				currentSkuIndex: -1,
				classifyList: [],
				skuForm: {
					name: '',
					originalPrice: '',
					discountPrice: '',
					repertory: ''
				},
				form: {
				  _id: '',
				  name: '',
				  banner: [],
				  details: [],
				  classify: [],
				  merchantId: '',
				  skuList: []
				},
				index: -1,
				modalName: null,
				bannerImgList: [],
				detailImgList: [],
				goodsUnits: ['g', 'kg', '件', '箱', '瓶', '升'],
				picker: ['喵喵喵', '汪汪汪', '哼唧哼唧'],
				uploadTaskList: [],
				baseUrl: config.network.imageUrl
			};
		},
		computed: {
			checkedClassifyList() {
				return this.classifyList.filter(item => item.checked);
			}
		},
		async onLoad(options) {
			let title = '';
			await this.initClassify();
			this.goodsId = options.id;
			if (this.goodsId && this.goodsId !== 'undefined') {
				title = '编辑商品';
				this.getGoodsDetail();
			} else {
				title = '添加商品';
			}
			uni.setNavigationBarTitle({
				title
			})
		},
		methods: {
			async getGoodsDetail() {
				const res = await goodsApi.findById(this.goodsId);
				const goods = res.data.data;
				this.form._id = goods._id;
				this.form.name = goods.name;
				this.bannerImgList = goods.banner.map(url => ({
					tempId: utils.uuid(),
					tempFile: this.baseUrl + url,
					complete: true,
					url: url.replace(/\/goods\//g, '')
				}));
				this.detailImgList = goods.details.map(url => ({
					tempId: utils.uuid(),
					tempFile: this.baseUrl + url,
					complete: true,
					url: url.replace(/\/goods\//g, '')
				}));
				console.log(this.bannerImgList);
				console.log(this.detailImgList);
				goods.classify.forEach(code => {
					this.classifyList.filter(item => item.code === code)[0].checked = true;
				})
				
				this.form.skuList = goods.skuList.map(({name, originalPrice, discountPrice, repertory}) => ({name, originalPrice, discountPrice, repertory}));
			},
			submitSkuForm() {
				let errMsg = '';
				if (isEmpty(this.skuForm.name)) {
					errMsg = '请输入规格名称';
				} else if (isEmpty(this.skuForm.originalPrice)) {
					errMsg = '请输入原价';
				} else if (isEmpty(this.skuForm.repertory)) {
					errMsg = '请输入库存';
				}
				if (errMsg) {
					return uni.showToast({
						title: errMsg,
						icon: 'none'
					})
				}
				if (this.currentSkuIndex === -1) {
					this.form.skuList.push(Object.assign({}, this.skuForm));
				} 
				this.clearSkuForm();
				this.currentSkuIndex === -1;
				this.hideModal();
			},
			clearSkuForm() {
				this.skuForm = {
					name: '',
					originalPrice: '',
					discountPrice: '',
					repertory: ''
				};
			},
			cancel() {
				uni.navigateBack();
			},
			async submitForm() {
				await Promise.all(this.uploadTaskList);
			    this.form.banner = this.bannerImgList.map(item => item.url);
				this.form.details = this.detailImgList.map(item => item.url);
				this.form.classify = this.checkedClassifyList.map(item => item.code);
				
				let errMsg = '';
				if (isEmpty(this.form.name)) {
					errMsg = '请输入商品名称';
				} else if (isEmpty(this.form.classify)) {
					errMsg = '请选择分类';
				} else if (isEmpty(this.form.banner)) {
					errMsg = '请上传轮播图';
				} else if (isEmpty(this.form.details)) {
					errMsg = '请上传详情图';
				} else if (isEmpty(this.form.skuList)) {
					errMsg = '请添加规格';
				}
				if (errMsg) {
					return uni.showToast({
						title: errMsg,
						icon: 'none'
					})
				}
				this.form.merchantId = uni.getStorageSync('merchantId');
				const res = await goodsApi.create(this.form);
				const data = res.data;
			
				if (data.code === 1) {
					// 清空数据
					if (this.form._id) {
						uni.$emit('resetList')
						uni.switchTab({
							url:'/pages/goods/goods'
						});
					} else {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/goods/form'
							})
						}, 1000);
					}
				}
				uni.showToast({
					title: data.msg,
					icon: 'none'
				})
			},
			editClassify() {
				this.hideModal();
			},
			chooseCheckbox(e) {
				let items = this.classifyList;
				let values = e.currentTarget.dataset.value;
				for (let i = 0, lenI = items.length; i < lenI; ++i) {
					if (items[i]._id == values) {
						items[i].checked = !items[i].checked;
						break
					}
				}
			},
			async initClassify() {
				const res = await goodsApi.getClassify();
				this.classifyList = res.data.data.map(item => ({
					...item,
					checked: false
				}));
			},
			deleteClassify(e) {
				e.preventDefault();
				e.stopPropagation();
				const index = e.currentTarget.dataset.index;
				const id = e.currentTarget.dataset.id;
				//this.checkedClassifyList.splice(index, 1);
				this.classifyList.filter(item => item._id === id)[0].checked = false;
			},
			deleteSku(e) {
				this.form.skuList.splice(e.currentTarget.dataset.index, 1);
			},
			showSkuModal(e) {
				this.currentSkuIndex = e.currentTarget.dataset.index;
				if (this.currentSkuIndex) {
					this.skuForm = this.form.skuList[this.currentSkuIndex];
				}  else {
					this.currentSkuIndex = -1;
					this.clearSkuForm();
				}
				this.showModal(e);
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			pickerChange(e) {
				this.index = e.detail.value
			},
			chooseImage(target) {
				const self = this;
				uni.chooseImage({
					count: 4,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						let tempId =  '';
						res.tempFilePaths.slice(0, 4).forEach(tempFile => {
							tempId = utils.uuid();
							self[`${target}ImgList`].push({
								tempId,
								tempFile,
								complete: false
							});
							self.uploadTaskList.push(self.requestUpload(tempFile, target, tempId));
						})
					}
				});
			},
			viewImage(e) {
				uni.previewImage({
					urls: this.bannerImgList,
					current: e.currentTarget.dataset.url
				});
			},
			delImg(e) {
				const dataset = e.currentTarget.dataset;
				this[`${dataset.target}ImgList`].splice(dataset.index, 1)
			},
			requestUpload(filePath, target, tempId) {
				return new Promise((resolve, reject) => {
					const self = this;
					uni.uploadFile({
						url: `${config.network.baseUrl}/system/upload`,
						filePath: filePath,
						name: 'file',
						success: res => {
							const data = JSON.parse(res.data);
							const currentImg = self[`${target}ImgList`].filter(item => item.tempId === tempId)[0];
							currentImg.complete = true;
							currentImg.url = data.data.filename;
							resolve();
						},
						fail(err) {
							reject(err);
						},
						complete(res) {
							if (res.statusCode !== 200) {
								uni.showToast({
									title: '系统异常：' + res.statusCode,
									icon: 'none'
								});
								reject();
							}
						}
					});
				});
			},
		}
	}
</script>

<style scoped lang="less">
	.bg-img{
		position: relative;
	}
	.shade{
		position: absolute;
		top: 0px;
		right: 0px;
		bottom: 0px;
		left: 0px;
		background-color: rgba(1, 1, 1, .5);
		z-index: 1;
	}
	.classify-list{
		display: flex;
		flex: 1;
		.classify-item{
			position: relative;
			color: #FFF;
			margin-right: 10px;
			padding: 5px 8px;
			.close-icon{
				position: absolute;
				top: -5px;
				right: -5px;
				font-size: 20px;
			}
		}
	}
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
	.sku-list{
		margin-top: 15px;
		padding: 15px;
		background-color: #FFF;
		.sku-title{
			display: flex;
			justify-content: space-between;
		}
		.sku-item{
			display: flex;
			margin-top: 10px;
			.name{
				flex: 1;
			}
			.price{
				flex: 1;
			}
			.count{
				flex: 1;
			}
			.title{
				
			}
			.operation{
				width: 80rpx;
				.icon:first-child{
					margin-right: 10px;
				}
			}
		}
	}
</style>
